package io.renren.modules.workflow.service.impl;


import com.caiap.activiti.domain.ActBusArchivesData;
import com.caiap.activiti.domain.ActBusWorkflowData;
import com.caiap.activiti.domain.archivesDto.ActDataMap;
import com.caiap.activiti.domain.archivesDto.ActStructure;
import com.caiap.activiti.enums.*;
import com.caiap.activiti.mapper.ActBusArchivesDataMapper;
import com.caiap.activiti.mapper.ActBusWorkflowDataMapper;
import io.renren.common.utils.AjaxResult;
import io.renren.modules.workflow.dao.ActBusWorkflowDataMapper;
import io.renren.modules.workflow.entity.ActBusWorkflowData;
import io.renren.modules.workflow.enums.ActOperationTypeEnum;
import io.renren.modules.workflow.service.IActBusArchivesDataService;
import com.caiap.common.annotation.DataScope;
import com.caiap.common.config.CAIAPConfig;
import com.caiap.common.core.domain.AjaxResult;
import com.caiap.common.core.domain.entity.SysUser;
import com.caiap.common.utils.DateUtils;
import com.caiap.common.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Desc 流程任务service实现
 * @Author landlord
 * @Date 2021/7/30 17:31
 */
@Service
public class ActBusArchivesDataServiceImpl implements IActBusArchivesDataService {

    @Autowired
    private ActBusWorkflowDataMapper actBusWorkflowDataMapper;




    /**
     * 新增流程业务数据
     *
     * @param actBusArchivesData 流程业务数据
     * @return 结果
     */
    @Override
    public AjaxResult insertActBusArchivesData(ActBusArchivesData actBusArchivesData){
        if(actBusArchivesData.getAbwdId()==null){
            return AjaxResult.error("流程单据信息获取失败");
        }
        int count = 0;      //申明数据条数
        actBusArchivesData.setCreateBy(SecurityUtils.getUsername());
        actBusArchivesData.setBusinessName(SecurityUtils.getUsername());
        actBusArchivesData.setBusinessDeptName(SecurityUtils.getLoginUser().getUser().getDept().getDeptName());
        actBusArchivesData.setBusTypeValue(ActBusTypeEnum.getBysTypeValue(Integer.valueOf(actBusArchivesData.getBusType())));
        actBusArchivesData.setCreateTime(DateUtils.getNowDate());
        List<Map<String,Object>> list = new ArrayList<>();
        //根据ID集查询业务数据
        if(ActBusinessTypeEnum.TRANSFER.getKey().equalsIgnoreCase(actBusArchivesData.getBusinessType())||
                ActBusinessTypeEnum.DESTROY.getKey().equalsIgnoreCase(actBusArchivesData.getBusinessType())) {
            if(actBusArchivesData.getParamIds()==null || actBusArchivesData.getParamIds().length<=0){
                return AjaxResult.error("获取数据失败,请重试");
            }
            list = actBusArchivesDataMapper.selectArchivesDataList(actBusArchivesData);
        }else if(ActBusinessTypeEnum.UTILIZE.getKey().equalsIgnoreCase(actBusArchivesData.getBusinessType())){
            if(actBusArchivesData.getUsingMap()==null || actBusArchivesData.getUsingMap().size()<=0){
                return AjaxResult.error("获取数据失败,请重试");
            }
            list = actBusArchivesData.getUsingMap();
        }
        if(list!=null && list.size()>0){
            for(Map<String,Object> map :list){
                // 赋值业务数据
                actBusArchivesData.setDataId(Long.valueOf(String.valueOf(map.get("ID"))));
                actBusArchivesData.setRecordId(StringUtils.isNotEmpty(String.valueOf(map.get("RECORDID")))?String.valueOf(map.get("RECORDID")):null);
                actBusArchivesData.setTitle(StringUtils.isNotEmpty(String.valueOf(map.get("TITLE")))?String.valueOf(map.get("TITLE")):null);
                actBusArchivesData.setStructureId(String.valueOf(map.get("STRUCTURE_ID")));
                actBusArchivesData.setStructureType(String.valueOf(map.get("STRUCTURE_TYPE")));
                //利用业务特殊处理
                if(ActBusinessTypeEnum.UTILIZE.getKey().equalsIgnoreCase(actBusArchivesData.getBusinessType())) {
                    actBusArchivesData.setTableName(String.valueOf(map.get("PATHS")));
                    actBusArchivesData.setFileState(String.valueOf(map.get("FILESTATE")));
                }
                count += actBusArchivesDataMapper.insertActBusArchivesData(actBusArchivesData);
            }
            if(count>0 && !ActBusinessTypeEnum.UTILIZE.getKey().equalsIgnoreCase(actBusArchivesData.getBusinessType())){
                //修改档案业务数据状态
                updateArchivesStatus(actBusArchivesData.getAbwdId(), ActOperationTypeEnum.SUBMIT , actBusArchivesData.getBusinessType());
            }
        }
        return AjaxResult.success(count);
    }

    /**
     * 修改流程业务数据
     *
     * @param actBusArchivesData 流程业务数据
     * @return 结果
     */
    @Override
    public int updateActBusArchivesData(ActBusArchivesData actBusArchivesData)
    {
        actBusArchivesData.setUpdateTime(DateUtils.getNowDate());
        return actBusArchivesDataMapper.updateActBusArchivesData(actBusArchivesData);
    }

    /**
     * 批量删除流程业务数据
     *
     * @param abwbdIds 需要删除的流程业务数据ID
     * @return 结果
     */
    @Override
    public int deleteActBusArchivesDataByIds(Long[] abwbdIds)
    {
        return actBusArchivesDataMapper.deleteActBusArchivesDataByIds(abwbdIds);
    }

    /**
     * 删除流程业务数据信息
     *
     * @param abwbdId 流程业务数据ID
     * @return 结果
     */
    @Override
    public int deleteActBusArchivesDataById(Long abwbdId)
    {
        return actBusArchivesDataMapper.deleteActBusArchivesDataById(abwbdId);
    }

    /**
     * 删除流程业务数据信息
     *
     * @param abwdId 流程业务数据ID
     * @return 结果
     */
    @Override
    public int deleteActBusArchivesDataByAbwdId(Long abwdId)
    {
        ActBusWorkflowData actBusWorkflowData = actBusWorkflowDataMapper.selectActBusWorkflowDataById(abwdId);
        updateArchivesStatus(abwdId, ActOperationTypeEnum.SUSPEND,actBusWorkflowData.getAbwdBusinessType());
        return actBusArchivesDataMapper.deleteActBusArchivesDataByAbwdId(abwdId);
    }


    /**
     * 获取移交接收的列表
     * @param actBusWorkflowData
     * @return
     */
    @DataScope(deptAlias = "ad",userAlias = "ad")
    public List<ActBusWorkflowData> selectTransferAndReceiveList(ActBusWorkflowData actBusWorkflowData){
        // 新增角色信息
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        actBusWorkflowData.setDeptId(sysUser.getDeptId());
        actBusWorkflowData.setUserId(sysUser.getUserId());
        actBusWorkflowData.setAbwdBusinessType(ActBusinessTypeEnum.TRANSFER.getKey());
        actBusWorkflowData.setAbwdWorkflowStatus(ActBusWorkFlowStatusEnum.PASS.getKey());
        actBusWorkflowData.setOrderBy("ABWD_BUSINESS_STATUS");  //默认排序为空业务状态正序
        return actBusWorkflowDataMapper.selectActBusWorkflowDataList(actBusWorkflowData);
    }


    /**
     * 获取移交接收的列表
     * @param actBusWorkflowData
     * @return
     */
    public List<ActBusWorkflowData> selectDestroyList(ActBusWorkflowData actBusWorkflowData){
        actBusWorkflowData.setAbwdBusinessType(ActBusinessTypeEnum.DESTROY.getKey());
        actBusWorkflowData.setAbwdWorkflowStatus(ActBusWorkFlowStatusEnum.PASS.getKey());
        actBusWorkflowData.setOrderBy("ABWD_BUSINESS_STATUS");  //默认排序为空业务状态正序
        return actBusWorkflowDataMapper.selectActBusWorkflowDataList(actBusWorkflowData);
    }


    /**
     * 获取集合数据
     * @param abwdId
     * @return
     */
    public ActBusArchivesData selectArchivesDataList(Long abwdId){
        ActBusArchivesData actBusArchivesData = new ActBusArchivesData();
        String dbTypy = CAIAPConfig.getDbType();
        List<ActBusArchivesData> list = new ArrayList<>();
        if (dbTypy.equalsIgnoreCase(ActBusDbTypeEnum.MYSQL.getKey())) {
            list = actBusArchivesDataMapper.selectActBusArchivesDataByAbwdIdByMysql(abwdId);
        } else if (dbTypy.equalsIgnoreCase(ActBusDbTypeEnum.OSCAR.getKey())) {
            list = actBusArchivesDataMapper.selectActBusArchivesDataByAbwdIdByDm(abwdId);
        } else if (dbTypy.equalsIgnoreCase(ActBusDbTypeEnum.DM.getKey())) {
            list = actBusArchivesDataMapper.selectActBusArchivesDataByAbwdIdByDm(abwdId);
        }
        actBusArchivesData = actBusArchivesDataMapper.selectActBusArchivesDataByAbwdIdByDetails(abwdId);
        if(list!=null && list.size()>0){
            Long[] ids = new Long[list.size()];
            for(int i=0; i<list.size();i++){
                ids[i] = list.get(i).getDataId();
            }
            actBusArchivesData.setIds(StringUtils.join(ids,","));
        }
        return actBusArchivesData;
    }

    /**
     * 档案业务数据状态扭转
     * @param abwdID    流程单据ID
     * @param operationTypeEnum    单据操作
     */
    public void updateArchivesStatus(Long abwdID,ActOperationTypeEnum operationTypeEnum ,String businessType) {
        ActBusArchivesData actBusArchivesData = new ActBusArchivesData();
        List<ActBusArchivesData> usingList = new ArrayList<>();
        try {
            //分库查询
            String dbTypy = CAIAPConfig.getDbType();
            List<ActBusArchivesData> list = new ArrayList<>();
            if (dbTypy.equalsIgnoreCase(ActBusDbTypeEnum.MYSQL.getKey())) {
                list = actBusArchivesDataMapper.selectActBusArchivesDataByAbwdIdByMysql(abwdID);
            } else if (dbTypy.equalsIgnoreCase(ActBusDbTypeEnum.OSCAR.getKey())) {
                list = actBusArchivesDataMapper.selectActBusArchivesDataByAbwdIdByDm(abwdID);
            } else if (dbTypy.equalsIgnoreCase(ActBusDbTypeEnum.DM.getKey())) {
                list = actBusArchivesDataMapper.selectActBusArchivesDataByAbwdIdByDm(abwdID);
            }
            actBusArchivesData = actBusArchivesDataMapper.selectActBusArchivesDataByAbwdIdByDetails(abwdID);
            if(list!=null && list.size()>0){
                Long[] ids = new Long[list.size()];
                for(int i=0; i<list.size();i++){
                    ids[i] = list.get(i).getDataId();
                }
                actBusArchivesData.setIds(StringUtils.join(ids,","));
            }
        }catch (Exception e){
            e.printStackTrace();
            //如果分库查询失败则直接返回
            return;
        }
        if(actBusArchivesData==null){
            return;
        }
        if (StringUtils.isNotEmpty(businessType) && !ActBusinessTypeEnum.UTILIZE.getKey().equalsIgnoreCase(businessType)) {
            //根据流程单获取的数据赋值给DataMap
            ActDataMap actDataMap = new ActDataMap();
            actDataMap.setTableName(actBusArchivesData.getTableName());
            actDataMap.setBusType(actBusArchivesData.getBusType());
            actDataMap.setBusTypeValue(ActBusTypeEnum.getBysTypeValue(Integer.valueOf(actBusArchivesData.getBusType())));
            actDataMap.setParamIds(actBusArchivesData.getIds().split(","));
            if (operationTypeEnum != null) {
                //获取档案业务数据状态扭转值
                switch (operationTypeEnum) {
                    case SUBMIT:    //如果操作类型为[提交],赋值相应的档案业务扭转状态
                        if (ActBusinessTypeEnum.TRANSFER.getKey().equalsIgnoreCase(businessType))
                            actDataMap.setStatusCode(String.valueOf(BusStateEnum.TRANSFERRING.getKey()));
                        else if (ActBusinessTypeEnum.DESTROY.getKey().equalsIgnoreCase(businessType))
                            actDataMap.setStatusCode(String.valueOf(BusStateEnum.DESTRUCTING.getKey()));
                        else if (ActBusinessTypeEnum.UTILIZE.getKey().equalsIgnoreCase(businessType))
                            actDataMap.setStatusCode(String.valueOf(BusStateEnum.UTILIZEAPR.getKey()));
                        break;
                    case SUSPEND:   //如果操作类型为[中止],赋值相应的档案业务扭转状态
                        if (ActBusinessTypeEnum.TRANSFER.getKey().equalsIgnoreCase(businessType))
                            actDataMap.setStatusCode(String.valueOf(BusStateEnum.ONLINE_COLLECTION.getKey()));
                        else if (ActBusinessTypeEnum.DESTROY.getKey().equalsIgnoreCase(businessType))
                            actDataMap.setStatusCode(String.valueOf(BusStateEnum.FILED.getKey()));
                        else if (ActBusinessTypeEnum.UTILIZE.getKey().equalsIgnoreCase(businessType))
                            actDataMap.setStatusCode(String.valueOf(BusStateEnum.FILED.getKey()));
                        break;
                    case AGREE:     //如果操作类型为[同意],赋值相应的档案业务扭转状态
                        if (ActBusinessTypeEnum.TRANSFER.getKey().equalsIgnoreCase(businessType)) {
                            actDataMap.setStatusCode(String.valueOf(BusStateEnum.TRANSFERRING.getKey()));
                        } else if (ActBusinessTypeEnum.DESTROY.getKey().equalsIgnoreCase(businessType)) {
                            actDataMap.setStatusCode(String.valueOf(BusStateEnum.DESTRUCTING.getKey()));
                        } else if (ActBusinessTypeEnum.UTILIZE.getKey().equalsIgnoreCase(businessType)) {
                            actDataMap.setStatusCode(String.valueOf(BusStateEnum.UTILIZEING.getKey()));
                        }
                        break;
                    case REFUSE:    //如果操作类型为[拒绝],赋值相应的档案业务扭转状态
                        if (ActBusinessTypeEnum.TRANSFER.getKey().equalsIgnoreCase(businessType)) {
                            actDataMap.setStatusCode(String.valueOf(BusStateEnum.ONLINE_COLLECTION.getKey()));
                        } else if (ActBusinessTypeEnum.DESTROY.getKey().equalsIgnoreCase(businessType)) {
                            actDataMap.setStatusCode(String.valueOf(BusStateEnum.FILED.getKey()));
                        } else if (ActBusinessTypeEnum.UTILIZE.getKey().equalsIgnoreCase(businessType)) {
                            actDataMap.setStatusCode(String.valueOf(BusStateEnum.FILED.getKey()));
                        }
                        break;
                }
            }

            //业务操作
            String[] ids = actDataMap.getParamIds();
            ActStructure actStructure = new ActStructure();
            actStructure.setTableName(actDataMap.getTableName());
            actStructure.setGroup(true);
            //获取结构信息,修改下级数据信息
            String[] tablePaths = actBusArchivesDataMapper.selectStructureByTableName(actStructure).getPaths().split("@");
            for (int j = 0; j < tablePaths.length; j++) {
                if (actDataMap.getTableName().equals(tablePaths[j])) {
                    actDataMap.setTableName(tablePaths[j]);
                    //修改业务数据状态值
                    actBusArchivesDataMapper.updateStatusByArchives(actDataMap);
                    if (j + 1 < tablePaths.length) {
                        actDataMap.setTableName(tablePaths[j + 1]);
                        //获取下级ID集合,如果集合为空,表示无下级数据,自动结束
                        ids = actBusArchivesDataMapper.getDataOfIds(actDataMap);
                        if (ids.length <= 0) {
                            break;
                        }
                        actDataMap.setParamIds(ids);
                    }
                }
            }
//            //利用操作 进行的业务流程
//            if(usingList!=null && usingList.size()>0 && businessType.equalsIgnoreCase(ActBusinessTypeEnum.UTILIZE.getKey())) {
//                for(ActBusArchivesData archivesData : usingList) {
//                    //业务操作
//                    String[] ids = actDataMap.getParamIds();
//                    ActStructure actStructure = new ActStructure();
//                    actStructure.setTableName(archivesData.getTableName());
//                    actStructure.setGroup(true);
//                    //获取结构信息,修改下级数据信息
//                    String[] tablePaths = actBusArchivesDataMapper.selectStructureByTableName(actStructure).getPaths().split("@");
//                    for (int j = 0; j < tablePaths.length; j++) {
//                        ActDataMap actDataMap = new ActDataMap();
//                        actDataMap.setTableName(actBusArchivesData.getTableName());
//                        actDataMap.setBusType(actBusArchivesData.getBusType());
//                        actDataMap.setBusTypeValue(ActBusTypeEnum.getBysTypeValue(Integer.valueOf(actBusArchivesData.getBusType())));
//                        actDataMap.setParamIds(actBusArchivesData.getIds().split(","));
//                        if (actDataMap.getTableName().equals(tablePaths[j])) {
//                            actDataMap.setTableName(tablePaths[j]);
//                            //修改业务数据状态值
//                            actBusArchivesDataMapper.updateStatusByArchives(actDataMap);
//                            if (j + 1 < tablePaths.length) {
//                                actDataMap.setTableName(tablePaths[j + 1]);
//                                //获取下级ID集合,如果集合为空,表示无下级数据,自动结束
//                                ids = actBusArchivesDataMapper.getDataOfIds(actDataMap);
//                                if (ids.length <= 0) {
//                                    break;
//                                }
//                                actDataMap.setParamIds(ids);
//                            }
//                        }
//                    }
//                }
//            }
//            //其他操作 进行的业务流程
//            else{
//            }
        }
    }

}
